/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package swa.e_store.application;

import java.util.ArrayList;
import java.util.Iterator;
import swa.e_store.data.Reorder;
import swa.e_store.data.OrderItem;
import javax.persistence.*;



/**
 * This class contains all business logic functionality related to orderings.
 * This can be Customer-Orders or ReOrdering from centralized Stock.
 * 
 * 
 * @author Stefan
 */
public class BL_Order {
    
    public static Reorder placeReorder(ArrayList<OrderItem> orderItemList, int USRID, String date){
        
        //EMFactory
        EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("Napier_E-StorePU");
        
        //EntityManager
        EntityManager eManager = emFactory.createEntityManager();
        
        //Start Transaction
        EntityTransaction tx = eManager.getTransaction();
        tx.begin();
        

        
        Reorder reorder = new Reorder(0, USRID, date);
        eManager.persist(reorder);       
        
        tx.commit();
        tx.begin();
        
        OrderItem tmpOItem = new OrderItem();
        
        Iterator<OrderItem> it = orderItemList.iterator();
        while (it.hasNext()) {
            tmpOItem = it.next();
            tmpOItem.setOrderId(reorder.getOrderId());
            eManager.persist(tmpOItem);
        }
        
        tx.commit();
        
        return reorder;
        
    }
    
}
